package lion.netty4.message;

import org.apache.commons.lang3.StringUtils;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.util.CharsetUtil;

public class SendToMessage {

	private ByteBuf buffer = null;

	private int msgCode = 0;

	private boolean messageFormated = false;

	public SendToMessage(ByteBufAllocator alloc, int pMsgCode) {
		buffer = alloc.buffer(64);
		// 保留0-5位
		buffer.writerIndex(4);
		setMsgCode(pMsgCode);
	}

	public ByteBuf entireMsg() {
		if (messageFormated) {
			ByteBuf bufferNew = buffer.duplicate();
			bufferNew.readerIndex(0);
			return bufferNew;
		}
		buffer.markWriterIndex();
		int currentPos = buffer.writerIndex();
		buffer.writerIndex(0);
		// 加入长度信息
		buffer.writeShort(getMsgCode());
		buffer.writeShort(currentPos);// package size
		buffer.resetWriterIndex();
		messageFormated = true;
		return buffer;
	}
	
	public void writeBoolean(boolean b) {
		buffer.writeBoolean(b);
	}
	
	public void writeShort(int i) {
		buffer.writeShort(i);
	}
	
	public void writeInt(int i) {
		buffer.writeInt(i);
	}

	public void writeLong(long i) {
		buffer.writeLong(i);
	}

	public void writeByte(byte i) {
		buffer.writeByte(i);
	}

	public int getMsgCode() {
		return msgCode;
	}

	public void setMsgCode(int msgCode) {
		this.msgCode = msgCode;
	}

	public void writeString(String str) {
		if (str == null || StringUtils.isEmpty(str)) {
			buffer.writeShort(0);
			return;
		}
		byte[] byteStr = str.getBytes(CharsetUtil.UTF_8);
		buffer.writeShort(byteStr.length);
		buffer.writeBytes(byteStr);
	}

	public void writeBytes(byte[] bytes) {
		buffer.writeShort(bytes.length);
		if (bytes.length > 0) {
			buffer.writeBytes(bytes);
		}
	}

}
